package saucaca.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import saucaca.CustomView.CircularImageView;
import saucaca.Database.DataBase;
import saucaca.Object.SongObject;
import saucaca.Util.FileUtils;
import saucaca.Util.PreferenceUtils;
import saucaca.Util.TagName;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.lemon.kenhnhacvn.BaseEngine;
import com.lemon.kenhnhacvn.MainActivity;
import com.lemon.kenhnhacvn.R;


public class LocalAllMusic extends Fragment {
	private static final String TAG = LocalAllMusic.class.getSimpleName();
	public static final String SONGS_MUSIC = "allmusic";
	public static final String ARTIST_MUSIC = "singermusic";
	public static final String ALBUM_MUSIC = "albummusic";
	public static final String FILE_MUSIC = "filemusic";
	public static final String PLAYLIST_MUSIC = "playlistmusic";
	public static final String VIDEO_MUSIC = "videomusic";
	
	public static final String Key_Title = "txt1";
	public static final String Key_Artist = "txt2";
	public static final String Key_Music = "music";
	public static final String Key_Image = "IMG";
	public static final String Key_List = "list";
	public static ArrayList<SongObject> mMusicList = new ArrayList<SongObject>();
	public static ArrayList<Map<String, Object>> allMusicMap = new ArrayList<Map<String, Object>>();
	public static ArrayList<Map<String, Object>> allVideoMap = new ArrayList<Map<String, Object>>();
	public static ArrayList<Map<String, Object>> singerMusicMap = new ArrayList<Map<String, Object>>();
	public static ArrayList<Map<String, Object>> albumMusicMap = new ArrayList<Map<String, Object>>();
	public static ArrayList<Map<String, Object>> fileMusicMap = new ArrayList<Map<String, Object>>();
	public static ArrayList<Map<String, Object>> playListMusicMap = new ArrayList<Map<String, Object>>();
	CircularImageView acountImage;
	TextView txtAllSong, txtBaihat, txtNghesy, txtAlbum, txtPlaylist, txtFolders, txtVideo;
	LinearLayout layoutBaihat, layoutNghesy, layoutAlbum, layoutPlaylist, layoutFolders, layoutVideo, layoutOnlineYeuthich, layoutOnlinePlaylist;
	public static DataBase db;
	static MainActivity mActivity;
	
	ImageLoader imageLoader;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	@SuppressLint("NewApi")
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		// return super.onCreateView(inflater, container, savedInstanceState);
//		getActivity().getActionBar().hide();
		View view = inflater.inflate(R.layout.song_local, container, false);
		findViewById(view);
		String strAvatar=PreferenceUtils.getString(mActivity, TagName.KeyPreference_avatar);
		String strAvatar_url=PreferenceUtils.getString(mActivity, TagName.KeyPreference_avatar_url);
		if(strAvatar!=null){
			try {
				Bitmap bitmap=BaseEngine.BitmapFromBase64(strAvatar);
				acountImage.setImageBitmap(bitmap);
			} catch (Exception e) {
			}
			mActivity.menuFragment.changedLoginstatus(true);
		}else if (strAvatar_url!=null) {
			mActivity.menuFragment.changedLoginstatus(true);
//			BaseActivity.imageLoader.displayImage(strAvatar_url, acountImage);
//			ImageLoader.getInstance().loadImage(strAvatar_url, new SimpleImageLoadingListener() {
//				@Override
//				public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
//					super.onLoadingComplete(imageUri, view, loadedImage);
//					PreferenceUtils.putString(mActivity, TagName.KeyPreference_avatar, BaseEngine.BitmapTobase64(loadedImage));
//					acountImage.setImageBitmap(loadedImage);
//				}
//			});
			
			imageLoader.get(strAvatar_url, new ImageLoader.ImageListener() {
		        @Override
		        public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
		        	PreferenceUtils.putString(mActivity, TagName.KeyPreference_avatar, BaseEngine.BitmapTobase64(response.getBitmap()));
					acountImage.setImageBitmap(response.getBitmap());
		        }

				@Override
				public void onErrorResponse(VolleyError arg0) {
				}
		    });
		}
		
		db = new DataBase(mActivity);
		initMediaData();
		txtAllSong.setText(Integer.toString(mMusicList.size()) + " " + mActivity.getResources().getString(R.string.number_song));
		txtBaihat.setText(Integer.toString(allMusicMap.size()));
		txtNghesy.setText(Integer.toString(singerMusicMap.size()));
		txtAlbum.setText(Integer.toString(albumMusicMap.size()));
		txtFolders.setText(Integer.toString(fileMusicMap.size()));
		txtPlaylist.setText(Integer.toString(playListMusicMap.size()));
		txtVideo.setText(Integer.toString(allVideoMap.size()));

		layoutBaihat.setOnClickListener(clickListener);
		layoutAlbum.setOnClickListener(clickListener);
		layoutFolders.setOnClickListener(clickListener);
		layoutNghesy.setOnClickListener(clickListener);
		layoutPlaylist.setOnClickListener(clickListener);
		layoutVideo.setOnClickListener(clickListener);

		layoutOnlineYeuthich.setOnClickListener(clickListener);
		layoutOnlinePlaylist.setOnClickListener(clickListener);
		mActivity.myActionBar.setMenu(R.string.menu_nhaccuatoi, false, true);
		return view;
	}
	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		if(!hidden){
			login();
			mActivity.myActionBar.setMenu(R.string.menu_nhaccuatoi, false, true);
		}
	}
	public void login(){
		String strAvatar=PreferenceUtils.getString(mActivity, TagName.KeyPreference_avatar);
		String strAvatar_url=PreferenceUtils.getString(mActivity, TagName.KeyPreference_avatar_url);
		if(strAvatar!=null){
			try {
				Bitmap bitmap=BaseEngine.BitmapFromBase64(strAvatar);
				acountImage.setImageBitmap(bitmap);
			} catch (Exception e) {
			}
			mActivity.menuFragment.changedLoginstatus(true);
		}else if (strAvatar_url!=null) {
			mActivity.menuFragment.changedLoginstatus(true);
//			BaseActivity.imageLoader.displayImage(strAvatar_url, acountImage);
//			ImageLoader.getInstance().loadImage(strAvatar_url, new SimpleImageLoadingListener() {
//				@Override
//				public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
//					super.onLoadingComplete(imageUri, view, loadedImage);
//					PreferenceUtils.putString(mActivity, TagName.KeyPreference_avatar, BaseEngine.BitmapTobase64(loadedImage));
//					acountImage.setImageBitmap(loadedImage);
//				}
//			});
			imageLoader.get(strAvatar_url, new ImageLoader.ImageListener() {
		        @Override
		        public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
		        	PreferenceUtils.putString(mActivity, TagName.KeyPreference_avatar, BaseEngine.BitmapTobase64(response.getBitmap()));
					acountImage.setImageBitmap(response.getBitmap());
		        }

				@Override
				public void onErrorResponse(VolleyError arg0) {
				}
		    });
		}
	}
	public void logout(){
		acountImage.setImageResource(R.drawable.cn_avatar_cover);
	}
	
	OnClickListener clickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
//			String contentFragment = LocalListFragment.class.getName();
			switch (v.getId()) {
			case R.id.offline_layout_baihat:
//				switchFragment(contentFragment, SONGS_MUSIC);
				switchFragment(SONGS_MUSIC);
				break;
			case R.id.offline_layout_album:
//				switchFragment(contentFragment, ALBUM_MUSIC);
				switchFragment(ALBUM_MUSIC);
				break;
			case R.id.offline_layout_folders:
//				switchFragment(contentFragment, FILE_MUSIC);
				switchFragment(FILE_MUSIC);
				break;
			case R.id.offline_layout_nghesy:
//				switchFragment(contentFragment, ARTIST_MUSIC);
				switchFragment(ARTIST_MUSIC);
				break;
			case R.id.offline_layout_playlist:
//				switchFragment(contentFragment, PLAYLIST_MUSIC);
				switchFragment(PLAYLIST_MUSIC);
				break;
			case R.id.offline_layout_video:
//				switchFragment(contentFragment, VIDEO_MUSIC);
				switchFragment(VIDEO_MUSIC);
				break;
			case R.id.online_layout_playlist:
				String user = PreferenceUtils.getString(getActivity(), TagName.KeyPreference_user);
				if (user != null)
					mActivity.switchContent(OnlinePlayListFragment.class.getName());
				else {
					new AlertDialog.Builder(mActivity).setTitle("Bạn chưa đăng nhập!").setMessage("Hãy đăng nhập để add playlist!")
							.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									mActivity.switchContent(AccountLoginFragment.class.getName());
								}
							}).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
								}
							}).setIcon(android.R.drawable.ic_dialog_alert).show();
				}
				break;
			case R.id.online_layout_baihatyeuthich:
				// switchFragment(contentFragment, VIDEO_MUSIC);
				break;
			default:
				break;
			}
		}
	};
	private void switchFragment(String fragment, String data) {
		if (mActivity == null) {
			return;
		} else if (mActivity instanceof MainActivity) {
			MainActivity a = (MainActivity) mActivity;
			a.switchContent(fragment, data);
		}
	}
	private void switchFragment(String content) {
		if (mActivity == null) {
			return;
		} else if (mActivity instanceof MainActivity) {
			MainActivity a = (MainActivity) mActivity;
			a.switchContent(LocalListFragment.newInstance(content));
		}
	}

	private void findViewById(View view) {
		txtAllSong = (TextView) view.findViewById(R.id.offline_mymusic_nubmer);
		txtBaihat = (TextView) view.findViewById(R.id.offline_text_baihat);
		txtAlbum = (TextView) view.findViewById(R.id.offline_text_album);
		txtNghesy = (TextView) view.findViewById(R.id.offline_text_nghesy);
		txtVideo = (TextView) view.findViewById(R.id.offline_text_video);
		txtPlaylist = (TextView) view.findViewById(R.id.offline_text_playlist);
		txtFolders = (TextView) view.findViewById(R.id.offline_text_folders);
		acountImage=(CircularImageView) view.findViewById(R.id.account_avatar);
		
		layoutBaihat = (LinearLayout) view.findViewById(R.id.offline_layout_baihat);
		layoutAlbum = (LinearLayout) view.findViewById(R.id.offline_layout_album);
		layoutFolders = (LinearLayout) view.findViewById(R.id.offline_layout_folders);
		layoutNghesy = (LinearLayout) view.findViewById(R.id.offline_layout_nghesy);
		layoutPlaylist = (LinearLayout) view.findViewById(R.id.offline_layout_playlist);
		layoutVideo = (LinearLayout) view.findViewById(R.id.offline_layout_video);

		layoutOnlinePlaylist = (LinearLayout) view.findViewById(R.id.online_layout_playlist);
		layoutOnlineYeuthich = (LinearLayout) view.findViewById(R.id.online_layout_baihatyeuthich);
		
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (activity instanceof MainActivity) {
			mActivity = (MainActivity) activity;
		}
	}


	@Override
	public void onStart() {
		super.onStart();
	}
	
	public static void initMediaData() {
		mMusicList.clear();
		allMusicMap.clear();
		singerMusicMap.clear();
		albumMusicMap.clear();
		fileMusicMap.clear();
		allVideoMap.clear();

//		String[] projection = {
//	            MediaStore.Audio.Media._ID,
//	            MediaStore.Audio.Media.ARTIST,
//	            MediaStore.Audio.Media.ALBUM,
//	            MediaStore.Audio.Media.TITLE,
//	            MediaStore.Audio.Media.DATA,
//	            MediaStore.Audio.Media.ALBUM_ID,
//	            MediaStore.Audio.Media.DURATION
//	    };
//	 
//	    Cursor cursor = mActivity.getContentResolver().query(
//	            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
//	            projection,
//	            MediaStore.Audio.Media.IS_MUSIC + " != 0",
//	            null,
//	            null);
		
		ContentResolver contentResolver = mActivity.getContentResolver();
		String[] projection = {
	            MediaStore.Audio.Media._ID,
	            MediaStore.Audio.Media.ARTIST,
	            MediaStore.Audio.Media.ALBUM,
	            MediaStore.Audio.Media.TITLE,
	            MediaStore.Audio.Media.DATA,
	            MediaStore.Audio.Media.DURATION
	    };
	    Cursor cursor = contentResolver.query(
	            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
	            projection,
	            MediaStore.Audio.Media.IS_MUSIC + " != 0",
	            null, MediaStore.Audio.Artists.DEFAULT_SORT_ORDER);
		

		// query all music
//		Cursor cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Audio.Media.IS_MUSIC);
		if (cursor == null)
			return;
		while (cursor.moveToNext()) {
			SongObject music = new SongObject();
			music.setSONG_ID(Integer.toString(cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID))));
			music.setTXNAME(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)));
			music.setNAME_SINGERS(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)));
			music.setALBUM(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM)));
			music.setPATCH_FULL(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)));
//			music.setSize(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));
			music.setduration(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
			music.setFormNet(false);
			mMusicList.add(music);

			Map<String, Object> map = new HashMap<String, Object>();
			map.put(Key_Title, music.getTXNAME());
			map.put(Key_Artist, music.getNAME_SINGERS());
			map.put(Key_Music, music);
			allMusicMap.add(map);
		}
		cursor.close();

		// query artist
		cursor = contentResolver.query(MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Audio.Artists.DEFAULT_SORT_ORDER);
		while (cursor.moveToNext()) {
			Map<String, Object> map = new HashMap<String, Object>();
			String singer = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Artists.ARTIST));
			String songcount = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Artists.NUMBER_OF_TRACKS));
			ArrayList<SongObject> musiclist = new ArrayList<SongObject>();
			for (int i = 0; i < mMusicList.size(); i++) {
				if (mMusicList.get(i).getNAME_SINGERS().equals(singer)) {
					musiclist.add(mMusicList.get(i));
				}
			}
			map.put(Key_Title, singer);
			map.put(Key_Artist, songcount + " " + mActivity.getResources().getString(R.string.number_song));
			map.put(Key_List, musiclist);
			singerMusicMap.add(map);
		}
		cursor.close();

		// query album
		cursor = contentResolver.query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Audio.Albums.DEFAULT_SORT_ORDER);
		while (cursor.moveToNext()) {
			Map<String, Object> map = new HashMap<String, Object>();
			String albumname = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM));
			String albumart = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM_ART));
			String singer = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ARTIST));

			ArrayList<SongObject> musiclist = new ArrayList<SongObject>();
			for (int i = 0; i < mMusicList.size(); i++) {
				if (mMusicList.get(i).getALBUM().equals(albumname)) {
					musiclist.add(mMusicList.get(i));
					mMusicList.get(i).setAVATAR(albumart);// add pic in song
				}
			}
			map.put(Key_Title, albumname);
			map.put(Key_Artist, singer);
			map.put(Key_Image, albumart);
			map.put(Key_List, musiclist);
			albumMusicMap.add(map);
		}
		cursor.close();

		// query video
		cursor = contentResolver.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Video.Media.DEFAULT_SORT_ORDER);
		while (cursor.moveToNext()) {
			SongObject music = new SongObject();
			music.setSONG_ID(Integer.toString(cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID))));
			music.setTXNAME(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME)));
			music.setPATCH_FULL(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA)));
			music.setNAME_SINGERS(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE)));
			music.setFormNet(false);

			Map<String, Object> map = new HashMap<String, Object>();
			map.put(Key_Title, music.getTXNAME());
			map.put(Key_Artist, music.getNAME_SINGERS());
			map.put(Key_Music, music);
			allVideoMap.add(map);
		}
		cursor.close();

		// file
		ArrayList<String> fileList = new ArrayList<String>();
		// list to store file url which contains music
		for (SongObject music : mMusicList) {
			String fileurl = FileUtils.getFileUrlString(music.getPATCH_FULL());
			if (!fileList.contains(fileurl))
				fileList.add(fileurl);
		}
		for (String url : fileList) {
			ArrayList<SongObject> fileMusic = new ArrayList<SongObject>();
			for (SongObject music : mMusicList) {
				if (url.equals(FileUtils.getFileUrlString(music.getPATCH_FULL())))
					fileMusic.add(music);
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put(Key_Title, FileUtils.getFileNameString(url));
			map.put(Key_Artist, url);
			map.put(Key_List, fileMusic);
			fileMusicMap.add(map);
		}

		// myplaylist
		refreshPlayList();
	}

	public static void refreshPlayList() {
		playListMusicMap.clear();
		ArrayList<String> playlistList = db.getMyPlayList();
		if (playlistList != null) {
			for (String playlist : playlistList) {
				ArrayList<SongObject> musicInPlayList = db.getMusicInPlayList(playlist);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put(Key_Title, playlist + "");
				map.put(Key_Artist, musicInPlayList.size() + " " + mActivity.getResources().getString(R.string.number_song));
				map.put(Key_List, musicInPlayList);
				playListMusicMap.add(map);
			}
		}
	}

	public static ArrayList<Map<String, Object>> getListShow(String stringShow) {
		if (stringShow.equals(ARTIST_MUSIC)) {
			return singerMusicMap;
		} else if (stringShow.equals(ALBUM_MUSIC)) {
			return albumMusicMap;
		} else if (stringShow.equals(FILE_MUSIC)) {
			return fileMusicMap;
		} else if (stringShow.equals(PLAYLIST_MUSIC)) {
			return playListMusicMap;
		} else if (stringShow.equals(VIDEO_MUSIC)) {
			return allVideoMap;
		} else
			return allMusicMap;
	}

}
